package org.rency.mq.activemq.listener.failover.impl;

import org.rency.mq.activemq.listener.failover.FailoverService;
import org.rency.mq.activemq.listener.failover.RetryStrategy;
import org.rency.mq.activemq.request.MQRequest;

public class AttenuationRetryStrategy extends DurationRetryStrategy implements RetryStrategy {
	private static final long DEFAULT_ATTENUATION_INTERVAL = 30;
    private float attenuationFactor = 2f;
    
    public AttenuationRetryStrategy(){
    	setInterval(DEFAULT_ATTENUATION_INTERVAL);
    }

	@Override
	protected void beforeProcess(MQRequest request) {
		long retryInterval = 0;
		
		if(request.containsProperty(FailoverService.AMQ_SCHEDULED_DELAY)){
			retryInterval = (long)((Long.parseLong(request.getProperty(FailoverService.AMQ_SCHEDULED_DELAY).toString()) * attenuationFactor));
		} else {
			retryInterval = getInterval() * 1000;
		}
		
		request.addProperty(FailoverService.AMQ_SCHEDULED_DELAY, retryInterval);
	}

	public float getAttenuationFactor() {
		return attenuationFactor;
	}

	public void setAttenuationFactor(float attenuationFactor) {
		if(attenuationFactor < 1){
			throw new IllegalArgumentException("Attenuation factor must be greater than 1.");
		}
		
		if(attenuationFactor > 0)
			this.attenuationFactor = attenuationFactor;
	}

}
